package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.User;
import utilities.ParametersValidator;
import utilities.ClientData;
import utilities.SafeSessionAccess;
import webSiteDataStore.FeedbackData;

public class Feedback extends HttpServlet 
{
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        ParametersValidator.ValidateProgrammerParameters(request, "mode");
        
        String mode = request.getParameter("mode");
        String presentationMedium  = ClientData.isMobileNativeClient(request) ? "mobile" : "desktop";
        String signature = "";
        if (mode.equals("getPostDetails") == false)
        {
            if (presentationMedium.equals("mobile"))
            {
                ParametersValidator.ValidateProgrammerParameters(request, "emailAddress");
                signature = request.getParameter("emailAddress");
                request.setAttribute("emailAddress", signature);
            }
            else // if (presentationMedium.equals("desktop"))
            {
                HttpSession session = request.getSession(false);
                User currentUser = (User)SafeSessionAccess.getAttribute(session, "user");
                signature = currentUser.getProfile().getEmailAddress(); // Email address to be used as signature.
            }      
        }
        
        if (mode.equals("getPostDetails"))
        {
            PrintWriter out = response.getWriter();
            try
            {
                ParametersValidator.ValidateProgrammerParameters(request, "postID");

                int postID = Integer.parseInt(request.getParameter("postID"));
                StringBuilder postsSubjectsBuilder = new StringBuilder("<dl>");
                ArrayList<model.Feedback> feedbacksList = FeedbackData.loadFeedback(postID);
                if (feedbacksList != null)
                {
                    for (model.Feedback feedback : feedbacksList)
                    {
                        postsSubjectsBuilder.append("<details id=\"");
                        postsSubjectsBuilder.append(feedback.getId());
                        postsSubjectsBuilder.append("\">");
                        postsSubjectsBuilder.append(feedback.getText());
                        postsSubjectsBuilder.append("</details>");
                    }
                }
                postsSubjectsBuilder.append("</dl>");

                response.setContentType("text/xml;charset=UTF-8");
                out.println("<?xml version=\"1.0\"?>");
                out.println(postsSubjectsBuilder.toString());
            }
            finally
            {
                out.close();
            }
        }
        else if (mode.equals("post"))
        {
            request.setAttribute("presentationMedium", presentationMedium);
            request.setAttribute("pageTitle", "User feedback");
            request.setAttribute("mode", "post");
            String nextPage = "/feedback.jsp";
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextPage);
            dispatcher.forward(request, response);
        }                
        else if (mode.equals("submit"))
        {
            ParametersValidator.ValidateProgrammerParameters(request, "subject", "text");
            
            String subject = request.getParameter("subject");
            String text = request.getParameter("text");

            java.util.Date time = new java.util.Date();
            model.Feedback feedback = new model.Feedback(subject, text, time, signature);
            FeedbackData.insertFeedback(feedback);
            
            request.setAttribute("presentationMedium", presentationMedium);
            request.setAttribute("pageTitle", "User feedback");
            request.setAttribute("mode", "post");
            String nextPage = "/feedback.jsp";
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextPage);
            dispatcher.forward(request, response);
        }                
        else if (mode.equals("read"))
        {
            StringBuilder postsSubjectsBuilder = new StringBuilder("<dl>");
            ArrayList<model.Feedback> feedbacksList = FeedbackData.loadFeedback(signature);
            if (feedbacksList != null)
            {
                for (model.Feedback feedback : feedbacksList)
                {
                    postsSubjectsBuilder.append("<dt id=\"");
                    postsSubjectsBuilder.append(feedback.getId());
                    postsSubjectsBuilder.append("\"><a href=\"#\">");
                    postsSubjectsBuilder.append(feedback.getSubject());
                    postsSubjectsBuilder.append("</a></dt>\n");
                }
            }
            postsSubjectsBuilder.append("</dl>");

            request.setAttribute("mode", mode);
            request.setAttribute("presentationMedium", presentationMedium);
            request.setAttribute("postsSubjects", postsSubjectsBuilder.toString());
            request.setAttribute("pageTitle", "User feedback");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/feedback.jsp");
            dispatcher.forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            Logger.getLogger(SignIn.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            Logger.getLogger(SignIn.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
